const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
require("dotenv").config();
const sequelize = require("./config/database");
const models = require("./models/init-models")(sequelize);
const mpRouter = require("./router/mp_router");
const adminRouter = require("./router/admin_router");
const adminVerifyTokenMiddleware = require("./middleware/adminVerifyTokenMiddlewares");
const mpVerifyTokenMiddlewares = require("./middleware/mpVerifyTokenMiddlewares");
const app = express();
app.use(cors());
app.use(morgan("tiny"));

// 将models挂载req请求对象身上
app.use((req, res, next) => {
  req.models = models;
  next();
});

app.use(express.static("assets"));
app.use("/uploads", express.static("./uploads"));

app.use("/admin", adminVerifyTokenMiddleware);

app.use("/mp", mpVerifyTokenMiddlewares);

// 注册后台路由中间件
app.use("/admin", adminRouter);

// 注册uniapp路由中间件

app.use("/mp", mpRouter);

// 程序中发生了错误，才会触发。如sql发生了错误
app.use((err, req, res, next) => {
  console.log(err);
  res.json({
    code: 20002,
    message: "服务器异常",
    data: {},
  });
});

app.listen(process.env.PORT, () => {
  console.log(`${process.env.ENVIRONMENT}已启动,端口为${process.env.PORT}`);
});
